import { checkCamera, checkPhotoLibrary, checkMakePhoneCall, checkLocationPermission, checkExternalStorage,checkRecorderManager } from './check';
import {gotoAppPermissionSetting} from './permission'

type ChooseImage = (params: Omit<UniNamespace.ChooseImageOptions, 'success' | 'fail' | 'complete'>) => Promise<UniApp.ChooseMediaSuccessCallbackResult>;

export const chooseImage: ChooseImage = (params) =>
	new Promise(async (resolve, reject) => {
		let hasMp = false;
		// #ifdef MP-WEIXIN
		hasMp = true;
		// #endif
		const api = hasMp ? uni.chooseMedia : uni.chooseImage;
		const _params = hasMp
			? {
					count: params['count'],
					mediaType: ['image'],
					sourceType: params['sourceType'],
					sizeType: params['sizeType']
			  }
			: params;

		type Params = typeof _params & {
			sizeType: string[];
			sourceType: UniNamespace.ChooseMediaOption['sourceType'];
			mediaType: UniNamespace.ChooseMediaOption['mediaType'];
		};
		// #ifdef APP
		try {
			if (!_params.sourceType) {
				await checkPhotoLibrary();
				await checkCamera();
			} else {
				if (_params.sourceType.includes('album')) {
					await checkPhotoLibrary();
				}
				if (_params.sourceType.includes('camera')) {
					await checkCamera();
				}
			}
		} catch (e) {
			reject(e);
			return;
		}
		// #endif
		api({
			...(_params as Params),
			success(res) {
				// #ifndef MP-WEIXIN
				res.tempFiles = res.tempFiles.map((item, index) => {
					return {
						...item,
						tempFilePath: (res as unknown as UniNamespace.ChooseImageSuccessCallbackResult).tempFilePaths[index] || item.tempFilePath|| item.path
					};
				});
				// #endif
				resolve(res);
			},
			fail(err: any) {
				console.log(err);
				reject(err);
			}
		});
	});

export const makePhoneCall = (params: Omit<UniNamespace.MakePhoneCallOptions, 'success' | 'fail' | 'complete'>) =>
	new Promise(async (resolve, reject) => {
		try {
			await checkMakePhoneCall();
		} catch (e) {
			reject(e);
			return;
		}
		uni.makePhoneCall({
			...params
		})
			.then((res) => {
				resolve(res);
			})
			.catch((err) => {
				console.log(err);
				reject(err);
			});
	});
type GetLocation = (params: Omit<UniNamespace.GetLocationOptions, 'success' | 'fail' | 'complete'>) => Promise<UniNamespace.GetLocationSuccess>;

export const getLocation: GetLocation = (params) =>
	new Promise(async (resolve, reject) => {
		try {
			await checkLocationPermission();
		} catch (e) {
			reject(e);
			return;
		}

		uni.getLocation({
			...params
		})
			.then((res: UniNamespace.GetLocationSuccess) => {
				resolve(res);
			})
			.catch(async (err: { code: number }) => {
				console.log(err);
				// #ifdef APP
				if (err.code !== 22) {
					uni.showToast({
						title: '获取定位失败，请检查是否已开启GPS',
						duration: 2000,
						position: 'bottom'
					});
				}
				// #endif
				reject(err);
			});
	});
type SaveImageToPhotosAlbum = (params: Omit<UniNamespace.SaveImageToPhotosAlbumOptions, 'success' | 'fail' | 'complete'>) => Promise<UniNamespace.SaveImageToPhotosAlbumResult>;

export const saveImageToPhotosAlbum: SaveImageToPhotosAlbum = (params) =>
	new Promise(async (resolve, reject) => {
		try {
			await checkExternalStorage();
		} catch (e) {
			reject(e);
			return;
		}

		uni.saveImageToPhotosAlbum({
			...params
		})
			.then((res: UniNamespace.SaveImageToPhotosAlbumResult) => {
				resolve(res);
			})
			.catch(async (err: { code: number }) => {
				console.log(err);
				reject(err);
			});
	});

type SaveVideoToPhotosAlbum = (params: Omit<UniNamespace.SaveVideoToPhotosAlbumOptions, 'success' | 'fail' | 'complete'>) => Promise<any>;

export const saveVideoToPhotosAlbum: SaveVideoToPhotosAlbum = (params) =>
	new Promise(async (resolve, reject) => {
		try {
			await checkExternalStorage();
		} catch (e) {
			reject(e);
			return;
		}

		uni.saveVideoToPhotosAlbum({
			...params
		})
			.then((res) => {
				resolve(res);
			})
			.catch(async (err: { code: number }) => {
				console.log(err);
				reject(err);
			});
	});

type SaveFile = (params: Omit<UniNamespace.SaveFileOptions, 'success' | 'fail' | 'complete'>) => Promise<any>;

export const saveFile: SaveFile = (params) =>
	new Promise(async (resolve, reject) => {
		// #ifdef H5
		
		// #endif
		// #ifndef H5
		try {
			await checkExternalStorage();
		} catch (e) {
			reject(e);
			return;
		}
		// #ifdef MP-WEIXIN
		uni.getFileSystemManager().saveFile({
			...params,
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
		// #endif
		// #ifndef MP-WEIXIN
		uni.saveFile({
			...params
		})
			.then((res) => {
				resolve(res);
			})
			.catch(async (err: { code: number }) => {
				console.log(err);
				reject(err);
			});
		// #endif

		// #endif
	});

export const getRecorderManager = async ():Promise<UniNamespace.RecorderManager> => {
	// #ifdef APP
	await checkRecorderManager();
	// #endif
	return uni.getRecorderManager()
}
const permisionMap:Record<string,() => Promise<boolean>> = {
    chooseVideo: async function() {
		await checkCamera();
        await checkPhotoLibrary();
		return true
    },
    saveImageToPhotosAlbum: checkExternalStorage,
    saveVideoToPhotosAlbum: checkExternalStorage,
    getLocation: checkLocationPermission,
    makePhoneCall: checkMakePhoneCall,
    
}

const addPermisionInterceptor = () => {
    Object.keys(permisionMap).forEach(key => {
		uni.addInterceptor(key, {
		    invoke(args) {
		        return new Promise((resolve, reject) => {
		            permisionMap[key]().then(() => {
						resolve(args)
					}).catch(() => {
						reject(args)
					})
		        });
		    },
		    fail(err) {
		        console.log('interceptor-fail', err)
		        if (err.errMsg.includes('fail No Permission')) {
		            uni.showModal({
		                title: '是否前往开启权限?',
		                cancelText: '否',
		                confirmText: '是',
		                success: (res) => {
		                    if (res.confirm) {
		                        gotoAppPermissionSetting()
		                    }
		                }
		            })
		        }
		    }
		})
	})
 
}
// #ifdef APP
addPermisionInterceptor()
// #endif